﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Home_AddNewBook : System.Web.UI.Page
{
    public List<PlatformEntity> listPlatform { get; set; }
    public BookAdapter adapter;
    public PlatformAdapter platformAdap;
    public LanguageManage Language;
    protected string savePathImage = "/Images/books/";
    protected string savePathData = "/Contents/";
    private int MaxImageSize = 900;
    private int MaxSize = 2000*1024; // 2M
    private UserEntity currentUser;
    public long bookID;
    public string title = "AddNewBook";
    public BookEntity currentBook = new BookEntity();

    protected void Page_Load(object sender, EventArgs e)
    {
        //check login
        currentUser = UserManager.Instance.Getuser();
        if (!currentUser.isLogin)
            Response.Redirect("~/Login.aspx");

        Language = new LanguageManage();
        platformAdap = new PlatformAdapter();
        btnCreate.Text = Language["Create"];        
        
        if (Request.QueryString["bookid"] != null)
        {
            title = "EditBook";
            btnCreate.Text = Language["Update"];
            bookID = Convert.ToInt32(Request.QueryString["bookid"]);
            currentBook = adapter.getBook(bookID)[0];
        }
        listPlatform = platformAdap.getListPlatform((long)Session["catelogyID"]);
    }

    public string isCheckPlatform(long platformID)
    {
        try
        {
            long count = currentBook.Details.Where(t => t.PlatformID == platformID).Count();
            if (count > 0)
                return "checked";
            else
            {
                return "";
            }
        }
        catch
        {
            return "";
        }
    }

    protected void btnCreate_Click(object sender, EventArgs e)
    {
        string pathImage = upImage.FileName;
        string pathData = upData.FileName;
        //Save image
        SaveImage();

        //Save data
        SaveData();
       adapter=new BookAdapter();
        try
        {
            currentBook.Name = Request.Form["txtName"].ToString();
            currentBook.Description = Request.Form["txtDescription"].ToString();
            if (pathData.Trim()!="")
            {
                currentBook.Link = savePathData + pathData;    
            }
            if (pathImage.Trim()!="")
            {
                currentBook.Image = savePathImage + pathImage;        
            }

            currentBook.CategoryID = (long) Session["catelogyID"];
            currentBook.NumberOfDownload = 0;
            currentBook.Active = false;
            currentBook.DateUpload = DateTime.Today;
            currentBook.UploadBy = currentUser.Account;
            currentBook.Author = UserManager.Instance.Getuser().Account;
            List<BookDetailEntity> Details = new List<BookDetailEntity>();
            
            currentBook.Details = Details;
            if (Request.QueryString["bookid"] == null)
            {
                for (int i = 0; i < listPlatform.Count(); i++)
                {
                    if (Request.Form["platform_" + listPlatform[i].ID] != null)
                    {
                        BookDetailEntity detail = new BookDetailEntity();
                        detail.PlatformID = listPlatform[i].ID;
                        Details.Add(detail);

                    }
                }
                //create book
                adapter.CreateBook(currentBook);
                Response.Redirect("~/Home/ListBooks.aspx?catelogyid=" + (long) Session["catelogyID"]);
            }
            else
            {
                for (int i = 0; i < listPlatform.Count(); i++)
                {
                    if (Request.Form["platform_" + listPlatform[i].ID] != null)
                    {
                        BookDetailEntity detail = new BookDetailEntity();
                        detail.PlatformID = listPlatform[i].ID;
                        detail.BookID = bookID;
                        Details.Add(detail);

                    }
                }
                //update book
                currentBook.ID = bookID;
                adapter.UpdateItem(currentBook);
                Response.Redirect("~/Home/ListBooks.aspx?catelogyid=" + (long)Session["catelogyID"]);
            }
        }
        catch (Exception)
        {

            throw;
        }
    }

    private void SaveImage()
    {
        try
        {
            String path = Server.MapPath("~" + savePathImage);
            String fileFullName = upImage.FileName;
            if (fileFullName != "")
            {
                String fileType = fileFullName.Substring(fileFullName.LastIndexOf('.'));
                String fileName = fileFullName.Substring(0, fileFullName.LastIndexOf('.'));

                // Get the bitmap data from the uploaded file
                Bitmap src = Bitmap.FromStream(upImage.PostedFile.InputStream) as Bitmap;

                // Resize the bitmap data
                Bitmap result = Utils.ResizeBitmap(src, MaxImageSize, MaxImageSize);

                // Check file with same name
                string saveName = path + fileFullName;
                int i = 2;
                while (true)
                {
                    if (File.Exists(saveName))
                    {
                        fileFullName = fileName + i.ToString() + fileType;

                        saveName = path + fileFullName;
                        i++;
                    }
                    else
                    {
                        break;
                    }
                }
                result.Save(saveName, ImageFormat.Jpeg);
            }
        }
        catch
        {
            upImage.Focus();
        }
    }

    private void SaveData()
    {
        try
        {
            String path = Server.MapPath("~" + savePathData);
            String fileFullName = upData.FileName;
            if (fileFullName != "")
            {
                String fileType = fileFullName.Substring(fileFullName.LastIndexOf('.'));
                String fileName = fileFullName.Substring(0, fileFullName.LastIndexOf('.'));


                // Check file with same name
                string saveName = path + fileFullName;
                int i = 2;
                while (true)
                {
                    if (File.Exists(saveName))
                    {
                        fileFullName = fileName + i.ToString() + fileType;

                        saveName = path + fileFullName;
                        i++;
                    }
                    else
                    {
                        break;
                    }
                }
                upImage.SaveAs(saveName);
            }
        }
        catch
        {
            upData.Focus();
        }
    }
}